package cn.galudisu.reactivemanifesto

import akka.actor.{Actor, ActorLogging}
import akka.http.scaladsl.model.Uri
import cn.galudisu.reactivemanifesto.event._
import cn.galudisu.reactivemanifesto.interceptor.InterceptorMagnet.{AC, Circuity, Zeroline}

import scala.concurrent.duration._
import scala.language.postfixOps
/**
  * 服务编排，备忘
  */
class Choreography extends Actor with ActorLogging {

  // 服务列表
  var apis: Map[Uri,Panel] = Map.empty

  override def receive: Receive = {

    case panel: Panel =>
      apis += (panel.uri -> panel)
    case booklet: Booklet =>
      sender() ! produce(booklet,apis)
    case _ =>
      log.error("error occur !!!!")
  }

  private[reactivemanifesto] def produce(booklet: Booklet, uriToPanel: Map[Uri, Panel]):Circuity = {
    import GospelConfig._

    // 可用的条数
    val rest = booklet.apis.filter{b =>
      val panel = uriToPanel.get(b)
      panel match {
        case Some(succ:Succ) if succ.status < 500 => true
        case Some(err:Err) => false
        case Some(tot: Tot) => false
        case Some(rec: Rec) => false
        case None => false
      }
    }

    // 都满足才说明服务可用
    if(rest.size == booklet.apis.size) {
      AC(name = booklet.name)
    }else {
      Zeroline(name =booklet.name, timeout = call_timeout.seconds)
    }
  }
}




